<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/my/my.css">
    <title>北京自考社区</title>
</head>

<style>
    .showQuestion {
        background-color: white;
        box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.04);
        padding: 16px 24px 36px;
        height: auto;
    }

    .showQuestion .title {
        color: #333;
        margin: 0 0 5px 0;
        font: normal 28px/36px "Microsoft YaHei";
    }

    .showQuestion p {
        /* height: 24px !important; */
        line-height: 24px !important;
        font-size: 14px;
        font-family: 'Microsoft YaHei', 'SF Pro Display', Roboto, Noto, Arial, 'PingFang SC', sans-serif;
        color: #333;
    }

    .showQuestion img {
        width: 100%;
        height: auto;
    }

    .toolbar {
        overflow: hidden;
    }

    .toolbar li {
        float: left;
        padding: 0px 4px;
    }

    .my-form-item label, .my-form-item button, .my-form-item textarea {
        display: block;
    }

    .my-form-item label {
        width: 40px;
        line-height: 38px;
        text-align: center;
        padding: 0px;
    }

    .my-form-item textarea {
        width: auto;
        min-width: 780px;
    }

    .my-form-item label, .my-form-item textarea {
        float: left;
    }

    .my-form-item button {
        float: right;
    }

    .showAnswer {
        margin-top: 12px;
        background-color: #FFFFFF;
    }

    .answer-item {
        border-bottom: 1px #E8E8ED solid;
        padding: 6px;
    }

    .remarkAnswerForm {
        display: none;
    }
    .answer-remark-item i,.answer-remark-item p{
        float: left;
    }
    .answer-remark-item{
        overflow: hidden;
    }

    .showQuestion .question_info {
        display: block;
        margin: 0 0 10px 0;
        color: #999;
        font: normal 12px/24px Helvetica, Tahoma, Arial, sans-serif;
    }
    .answer_info {
        display: block;
        margin: 0 0 10px 0;
        color: #999;
        font: normal 12px/24px Helvetica, Tahoma, Arial, sans-serif;
    }
    .question-tool-bar{
        margin-top: -20px;
        margin-left: 4px;
        line-height: 16px;
        font-size: 16px;
    }
    .question-tool-bar a{
        padding: 0px 6px;
    }
</style>

<body>
<!-- header -->
<th:block th:include="common::header"></th:block>
<!-- main -->
<div class="layui-container re-layui-container my-main">
    <div class="my-main-content">
        <!-- 问题显示区域 -->
        <div class="showQuestion" id="showQuestion"></div>
        <div class="question-tool-bar">
            <a href="javascript:;" id="praiseIcon"><i class="layui-icon layui-icon-praise"></i><span id="praiseText">点赞</span><span id="praiseNum" th:text="${praiseNum}"></span></a>
            <a href="javascript:;" id="collectIcon"><i class="layui-icon layui-icon-star"></i><span>收藏</span><span id="collectNum" th:text="${collectNum}"></span></a>
            <a href='javascript:;' id="answerIcon"><i class="layui-icon layui-icon-reply-fill"></i><span>回答</span><span id="answerNum" th:text="${answerNum}"></span></a>
        </div>
        <!-- 回答显示区域 -->
        <div class="showAnswer" id="showAnswer">
            <div th:each="answer:${answers}" class="answer-item">
                <h2 th:if="${answer.isAccept} == 1" style="color: #5FB878;font-weight: bold;">被采纳</h2>
                <h4 class="answer_info" th:text="${answer.userName}+' '+${#dates.format(answer.createTime, 'yyyy-MM-dd HH:mm:ss')}+':'"></h4>
                <p th:utext="${answer.content}"></p><br/>
                <ul class='toolbar'>
                    <li th:if="${status} == 0">
                        <button th:if="${#httpSession.getAttribute('user')} and (${questionUserId} == ${(#httpSession.getAttribute('user')).id})" th:onclick="'javascript:accept(\''+${answer.id}+'\');'" class="layui-btn layui-btn-sm">采纳</button>
                    </li>
                </ul>
            </div>
        </div>
        <div class="layui-form-item my-form-item">
            <form th:if="${status} == 0" class="layui-form" style="margin-top: 12px;background-color: #FFFFFF" lay-filter="answerQuestionForm"
                  action="javascript:;">
                <textarea name="content" id="answerQuestion" class="layui-textarea"></textarea>
                <button style="position: relative;top:-42px;left: -4px" lay-submit lay-filter="answerQuestionBtn"
                        class="layui-btn layui-btn-primary">回答
                </button>
            </form>
        </div>
    </div>
    <div class="my-main-side">
        <div class="my-main-side-div">
            <div style="padding: 6px" class="my-adorn-status">
                <p style="font-weight: bold">今日推荐</p>
                <ul id="recomends">

                </ul>
            </div>
            <div style="padding: 6px"  class="my-adorn-recom">
                <p style="font-weight: bold">热门问答</p>
                <ul id="hots">
                </ul>
            </div>
        </div>
    </div>
</div>

<!-- footer -->
<th:block th:include="common::footer"></th:block>
</body>
<script src="/jquery-3.5.1.js"></script>
<script src="/layui/layui.js"></script>
<script src="/my/my.js"></script>

<script th:inline="javascript">
    var isPraise = 0;
    var isCollect = 0;

    var user = [[${#httpSession.getAttribute('user')}]];
    var status = [[${status}]];
    var questionId = [[${questionId}]];
    var praiseNum = [[${praiseNum}]];
    var collectNum = [[${collectNum}]];
    var answerNum = [[${answerNum}]];

    //页面加载完成出发
    $(document).ready(function () {
        var questionId = [[${questionId}]];
        $.ajax({
            url: '/question/question/info/' + questionId,
            type: 'get',
            contentType: "application/json;charset=UTF-8",
            success: function (obj) {
                status = obj.question.status;
                console.log("obj:",obj);
                $("#showQuestion").html("");
                if (status == 1){
                    $("#showQuestion").append("<h2 th:if=\"${status} == 1\" style=\"color: #5FB878;font-weight: bold;\">该问题已结束</h2><br/>");
                }

                $("#showQuestion").append("<h2 class='title'>" + obj.question.title + "</h2>")
                    .append("<h4 class='question_info'>发表于: " + new Date(obj.question.createTime).Format("yyyy-MM-dd hh:mm:ss") + " | 作者："+obj.question.userName+" </h4>")
                    .append(obj.question.content);
            }
        })

        // 渲染今日推荐
        $.ajax({
            url: '/question/question/recommends',
            type: 'get',
            contentType: "application/json;charset=UTF-8",
            success: function (items) {
                var _html = '';
                $.each(items,function (idx,item) {
                    _html += '<li style="margin: 6px 0px;cursor: pointer;"><a href="/question/question/showQuestion/'+item.id+'" target="_blank" class="layui-table-link">'+item.title+' </a><img style="width:14px;height: 14px;margin-top: -2px;" src="/images/readCountWhite.png"/>'+ item.pv + '</li>'
                })
                $("#recomends").html(_html);
            },
            error: function () {
                var _html = '<li>数据加载异常</li>';
                $("#recomends").html(_html);
            }
        });
        // 渲染热门问题
        $.ajax({
            url: '/question/question/hots',
            type: 'get',
            contentType: "application/json;charset=UTF-8",
            success: function (items) {
                var _html = '';
                $.each(items,function (idx,item) {
                    _html += '<li style="margin: 6px 0px;cursor: pointer;"><a href="/question/question/showQuestion/'+item.id+'" target="_blank" class="layui-table-link">'+item.title+' </a><img  style="width:14px;height: 14px;margin-top: -2px;" src="/images/readCountWhite.png"/>'+ item.totalPv + '</li>'
                })
                $("#hots").html(_html);
            },
            error: function () {
                var _html = '<li>数据加载异常</li>';
                $("#hots").html(_html);
            }
        });
        // 渲染问题工具条
        render_question_tool_bar();
    })

    // 渲染文章工具条
    function render_question_tool_bar(){
        // 渲染点赞
        if (user) {
            var praiseData = {
                "question_id":questionId,
                "user_id":user.id
            }
            $.ajax({
                url: '/question/praise2/selectByMap',
                type: 'post',
                contentType: "application/json;charset=UTF-8",
                data: JSON.stringify(praiseData),
                success: function (obj) {
                    if (obj.code == 200 && obj.praiseList.length == 1){
                        $("#praiseText").html("已赞");
                        $("#praiseNum").html(praiseNum);
                        isPraise = 1;
                    }else{
                        $("#praiseText").html("点赞");
                        $("#praiseNum").html(praiseNum);
                        isPraise = 0;
                    }
                }
            });
        }
        // 渲染收藏
        if (user) {
            var collectData = {
                "question_id":questionId,
                "user_id":user.id
            }
            $.ajax({
                url: '/question/collect2/selectByMap',
                type: 'post',
                contentType: "application/json;charset=UTF-8",
                data: JSON.stringify(collectData),
                success: function (obj) {
                    if (obj.code == 200 && obj.collectList.length == 1){
                        $("#collectIcon i").removeClass("layui-icon-star");
                        $("#collectIcon i").addClass("layui-icon-star-fill");
                        $("#collectNum").html(collectNum);
                        isCollect = 1;
                    }else{
                        $("#collectIcon i").removeClass("layui-icon-star-fill");
                        $("#collectIcon i").addClass("layui-icon-star");
                        $("#collectNum").html(collectNum);
                        isCollect = 0;
                    }
                }
            });
        }
    }

    // 设置一个页面定时器,用于统计pv
    var timeoutId = setTimeout(function () {
        var questionId = [[${questionId}]];
        $.get('/question/question/statistics/pv/' + questionId, function (data, status) {
            console.log("Data: " + data + "\nStatus: " + status);
        });
    }, 10000);

    layui.use(['form', 'layedit', 'layer', 'element'], function () {
        var form = layui.form;
        var layedit = layui.layedit;
        var layer = layui.layer;
        var element = layui.element;

        var index = layedit.build('answerQuestion');
        console.log("index:",index);

        // 监听点赞图标
        $(document).on('click','#praiseIcon',function(){
            if (!user) {
                layer.open({
                    type: 0,
                    content: "登录后才能点赞"
                });
                return;
            }

            var praiseData = {
                "questionId":questionId,
                "userId":user.id
            };
            if (!isPraise){
                $.ajax({
                    url: '/question/praise2/save',
                    type: 'post',
                    contentType: "application/json;charset=UTF-8",
                    data: JSON.stringify(praiseData),
                    success: function (obj) {
                        if (obj.code == 200){
                            praiseNum += 1;
                            render_question_tool_bar();
                        }
                    }
                });
            }else{
                $.ajax({
                    url: '/question/praise2/removeObj',
                    type: 'post',
                    contentType: "application/json;charset=UTF-8",
                    data: JSON.stringify(praiseData),
                    success: function (obj) {
                        if (obj.code == 200){
                            praiseNum -= 1;
                            render_question_tool_bar();
                        }
                    }
                });
            }

        });

        // 监听收藏图标
        $(document).on('click','#collectIcon',function(){
            var user = [[${#httpSession.getAttribute('user')}]];
            if (!user) {
                layer.open({
                    type: 0,
                    content: "登录后才能收藏"
                });
                return;
            }

            var collectData = {
                "questionId":questionId,
                "userId":user.id
            };
            if (!isCollect){
                $.ajax({
                    url: '/question/collect2/save',
                    type: 'post',
                    contentType: "application/json;charset=UTF-8",
                    data: JSON.stringify(collectData),
                    success: function (obj) {
                        if (obj.code == 200){
                            collectNum += 1;
                            render_question_tool_bar();
                        }
                    }
                });
            }else{
                $.ajax({
                    url: '/question/collect2/removeObj',
                    type: 'post',
                    contentType: "application/json;charset=UTF-8",
                    data: JSON.stringify(collectData),
                    success: function (obj) {
                        if (obj.code == 200){
                            collectNum -= 1;
                            render_question_tool_bar();
                        }
                    }
                });
            }
        });

        // 监听回答图标
        $(document).on('click','#answerIcon',function(){
            if (status == 1){
                layer.open({
                    type: 0,
                    content: "已结束的问题不可回答"
                });
                return;
            }

            var user = [[${#httpSession.getAttribute('user')}]];
            if (!user) {
                alert("请先登录");
            }else{
                // $("#answerQuestion").focus();  // 由于被layedit处理过，该方法已失效
                // contenteditable 属性是 HTML5 中的新属性
                // layedit是利用iframe来实现的，我们可以使用jquery来获取iframe的body,在iframe的body节点上触发焦点事件
                // 获取layedit iframe 中的元素，并触发焦点事件
                $("#LAY_layedit_"+index).contents().find("body").focus();
            }
        });

        form.on('submit(answerQuestionBtn)', function (data) {
            data.field.content = layedit.getContent(index);
            var questionId = [[${questionId}]];

            var answerData = {
                "content": data.field.content,
                "questionId": questionId,
            }
            console.log(answerData);

            $.ajax({
                url: '/question/answer/save',
                type: 'post',
                async:false,
                contentType: "application/json;charset=UTF-8",
                data: JSON.stringify(answerData),
                success: function (data) {
                    if (data.code == 200) {
                        layer.open({
                            type: 0,
                            content: "提交成功"
                        });
                    } else {
                        layer.open({
                            type: 0,
                            content: "提交失败"
                        });
                    }
                }
            })
            window.location.reload();
        });
    });

    // 采纳答案
    function accept(param) {
        var user = [[${#httpSession.getAttribute('user')}]];
        if (!user) {
            alert("请先登录");
        }else{
            var acceptData = {
                "id":param,
                "isAccept":1,
                "questionId":questionId
            }
            $.ajax({
                url: '/question/answer/accept',
                type: 'post',
                contentType: "application/json;charset=UTF-8",
                data: JSON.stringify(acceptData),
                success: function (obj) {
                    if (obj.code == 200){
                        layer.open({
                            type: 0,
                            content: "操作成功"
                        });
                    }
                }
            });
        }
        window.location.reload();
    }

    function remarkAnswerBtn(param) {
        if (remarkAnswerBtn_param && remarkAnswerBtn_param == param) {
            remarkAnswerBtn_param = null;
            $("#remarkAnswerForm-" + param).css("display", "none");
        } else {
            remarkAnswerBtn_param = param;
            $("#remarkAnswerForm-" + param).css("display", "block");
        }
    }

    // 用于保存函数remarkAnswerBtn的参数
    var remarkAnswerBtn_param = null;
    function remarkAnswer(param) {
        var content = $("#remarkAnswer-" + param).val();
        var answerId = param;
        var remarkData = {
            "answerId": answerId,
            "content": content
        }
        $.ajax({
            url: "/question/remark2/save",
            contentType: "application/json;charset=UTF-8",
            dataType: "预期服务器返回数据的类型",
            type: "post",
            data: JSON.stringify(remarkData),
            success: function (data) {
                if (data.code == 0) {
                    layer.open({
                        type: 0,
                        content: "评论成功"
                    });
                } else {
                    layer.open({
                        type: 0,
                        content: "评论失败"
                    });
                }
            },
            error: function () {
            }
        });
        return false;
    }
</script>

</html>